﻿using System;
using System.Collections.Generic;
using System.ServiceModel.Dispatcher;
using System.Web.Script.Serialization;

namespace Billing.Service.Wcf
{
    /// <summary>
    /// This class converts a parameter in a query string to an object of the appropriate type. 
    /// It can also convert a parameter from an object to its query string representation.
    /// Overrides class QueryStringConverter to specify the types to  be serialized on the wcf service and how to serialize them.
    /// </summary>
    public class WcfServiceQueryStringConverter : QueryStringConverter
    {
        #region Properties

        /// <summary>
        /// The list of available types to be used.
        /// </summary>
        private readonly List<Type> availableTypes = new List<Type>()
        {
        };

        #endregion

        /// <summary>
        /// Determines whether the specified type can be converted to and from a string representation.
        /// </summary>
        /// <param name="type">The System.Type to convert.</param>
        /// <returns>A value that specifies whether the type can be converted.</returns>
        public override bool CanConvert(Type type)
        {
            return (this.availableTypes.Exists(avType => avType == type) == true) || base.CanConvert(type);
        }
        /// <summary>
        /// Converts a query string parameter to the specified type.
        /// </summary>
        /// <param name="parameter">The string form of the parameter and value.</param>
        /// <param name="parameterType">The System.Type to convert the parameter to.</param>
        /// <returns>The converted parameter.</returns>
        public override object ConvertStringToValue(string parameter, Type parameterType)
        {
            object objectParsed;
            Type availableType = this.availableTypes.Find(avType => avType == parameterType);

            if (availableType == null)
            {
                objectParsed = base.ConvertStringToValue(parameter, parameterType);
            }
            else if (string.IsNullOrWhiteSpace(parameter) == false)
            {
                //Use a java script serializer because the incomming string is a json object.
                JavaScriptSerializer serializer = new JavaScriptSerializer();

                objectParsed = serializer.Deserialize(parameter, availableType);
            }
            else
            {
                objectParsed = null;
            }

            return objectParsed;
        }
    }
}
